package com.ncst.mvcweb.controller;

import com.ncst.mvcweb.entity.Product;
import com.ncst.mvcweb.service.ProductService;
import com.ncst.mvcweb.utils.ImageUtils;
import com.ncst.mvcweb.vo.JsonResult;
import com.ncst.mvcweb.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    // 图片存储根目录
    private static final String IMAGE_BASE_PATH = "D:/mvcweb/images";
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    @GetMapping(value = "/list")
    public PageResult<Product> list(int pageSize, int pageNumber) {
        Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id");
        PageRequest page = PageRequest.of(pageNumber, pageSize, Sort.by(order));
        Page<Product> page1 = productService.queryByPage(page);
        return new PageResult<>(page1.getNumberOfElements(), page1.getContent());
    }

    @GetMapping("queryProductById")
    public Product queryUserById(Integer id){
        return productService.queryById(id);
    }

    @PostMapping("deleteByList")
    public JsonResult deleteByList(@RequestParam("idList[]") List<Integer> idList){
        try {
            productService.delete(idList);
            return new JsonResult("success", "删除成功");
        } catch (Exception e) {
            return new JsonResult("fail", "删除失败:"+e.getMessage());
        }
    }

    @PostMapping("save")
    public JsonResult save(Product product, @RequestParam(value = "productImage", required = false) MultipartFile imageFile){
        try {
            // 处理图片上传
            if (imageFile != null && !imageFile.isEmpty()) {
                String imagePath = saveImage(imageFile);
                if (imagePath != null) {
                    product.setPicPath(imagePath);
                }
            }
            
            productService.save(product);
            return new JsonResult("success", "保存成功");
        } catch (Exception e) {
            return new JsonResult("fail", "保存失败:"+e.getMessage());
        }
    }

    /**
     * 保存图片文件
     * @param file 上传的文件
     * @return 保存后的相对路径
     */
    private String saveImage(MultipartFile file) {
        try {
            // 检查文件类型
            if (!ImageUtils.isValidImage(file.getContentType())) {
                throw new IllegalArgumentException("只支持图片文件");
            }

            // 检查文件大小
            if (!ImageUtils.isValidFileSize(file.getSize(), MAX_FILE_SIZE)) {
                throw new IllegalArgumentException("图片文件大小不能超过5MB");
            }

            // 生成存储路径
            String imagePath = ImageUtils.generateImagePath(file.getOriginalFilename());
            String fullPath = IMAGE_BASE_PATH + "/" + imagePath;
            
            // 创建目录
            Path directory = Paths.get(fullPath).getParent();
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }

            // 保存文件
            Path filePath = Paths.get(fullPath);
            Files.copy(file.getInputStream(), filePath);

            // 返回相对路径（用于数据库存储）
            return imagePath;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取图片资源
     * @param imagePath 图片路径
     * @return 图片字节数组
     */
    @GetMapping("/images/**")
    public byte[] getImage(HttpServletRequest request) throws IOException {
        String requestURL = request.getRequestURL().toString();
        String imagePath = requestURL.substring(requestURL.indexOf("/images/") + 8);
        
        Path fullPath = Paths.get(IMAGE_BASE_PATH, imagePath);
        
        if (Files.exists(fullPath)) {
            return Files.readAllBytes(fullPath);
        } else {
            throw new IOException("图片文件不存在");
        }
    }
}

